/**
 * JS工具类 调用方式
 * Util.validateReg.NumGreater1(参数)
 * @author mahd at 2015/11/22 10:38
 *
 */

var pageContent = new Array();
//默认的提示信息定义
var isIe=(document.all)?true:false;
var tipArray=[
    "确认",//0
    "取消",//1
    "关闭",//2
    "温馨提示"//3
];

Util={
    //验证
    validateReg:{
        //验证是否为空
        NotEmpty:function NotEmpty(obj){
            return obj!=null && $.trim(obj)!='';
        },
        //验证数字且必须大于1 并且第一位不能是0 支持小数点 不支持0.开头
        RegNumOrDouble:function RegNumOrDouble(obj){
            if(/^[1-9]+[0-9]*(([.]?\d+)|(\d*))$/.test(obj)){
                return true;
            }else{
                return false;
            }
        },
        //验证是否数字
        RegNumOrDouble2:function RegNumOrDouble2(obj){
            if(/^[0-9]+(([.]?\d+)|(\d*))$/.test(obj)){
                return true;
            }else{
                return false;
            }
        },
        //正整数判断
        RegNum:function RegNum(obj){
            if(/^[1-9]+[0-9]*$/.test(obj)){
                return true;
            }else{
                return false;
            }
        }
    },
    //时间处理
    date:{
    },
    //小数格式化
    Fmoney:function Fmoney(obj,radix){
        return parseFloat(obj).toFixed(radix);
    },
    common: {
        /**
         * 当前需要选中的导航菜单
         *
         * @param first_id   一级菜单id
         * @param second_id  二级菜单id
         * @constructor
         */
        CurrentMenu: function CurrentMenu(first_id, second_id) {
            var fath = $(".MyMuenLeft");
            //先移除所有一级选项卡高亮样式
            fath.children("div").children("a:first-child").removeClass("cur");
            //收起所有菜单
            packUpAllMenu();
            //高亮一级菜单
            $("#" + first_id).children("a:first-child").addClass("cur");
            //打开一级菜单，并高亮显示二级菜单
            openSecondMenu(first_id, second_id);
        },
        IsIE: function IsIE() {
            var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
            while (
                div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
                    all[0]
                );
            return v > 4 ? v : ("ActiveXObject" in window);
        },
        GetObjectURL: function GetObjectURL(file) {
            var url = null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file);
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file);
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file);
            }
            return url;
        },
        RevokeObjectURL: function RevokeObjectURL(file) {
            if (window.createObjectURL != undefined) {
                window.revokeObjectURL(file);
            } else if (window.URL != undefined) {
                window.URL.revokeObjectURL(file);
            } else if (window.webkitURL != undefined) {
                window.webkitURL.revokeObjectURL(file);
            }
        },
        FileSize: function FileSize(fileElement) {
            var file_size = 0;
            try {
                if(fileElement.files[0].size){
                    file_size = fileElement.files[0].size;
                }
            } catch (e) {
                var sh = setInterval(
                    function(){
                        fileElement.select();
                        top.parent.document.body.focus();
                        var src = document.selection.createRange().text;
                        var img = document.createElement("img");
                        img.src = src;
                        file_size = img.fileSize;
                        img = null;
                    }
                    ,100
                );
            }

            return file_size;
        },
        PreviewImage: function ReviewImage(fileElement, divShow, imgShow, width, height){
            var file_size = 0;
            if (fileElement.value) {
                if (Util.common.IsIE()) {
                    try {
                        file_size = this.files[0].size;
                        document.getElementById(imgShow).src = Util.common.GetObjectURL(fileElement.files[0]);
                        Util.common.RevokeObjectURL(fileElement.files[0]);
                    } catch (e) {
                        var div = document.getElementById(divShow);
                        fileElement.select();
                        top.parent.document.body.focus();
                        var src = document.selection.createRange().text;
                        var sh = setInterval(
                            function(){
                                var img = document.createElement("img");
                                img.src = src;
                                file_size = img.fileSize;
                                document.getElementById("fileSize").innerHTML = (Math.round(file_size * 100 / 1024) / 100).toString() + 'KB';;

                                img = null;
                            }
                            ,100
                        );

                        document.selection.empty();
                        document.getElementById(imgShow).style.display = "none";
                        div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                        div.style.width = width + "px";
                        div.style.height = height + "px";
                        div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src;
                    }
                } else {
                    file_size = fileElement.files[0].size;
                    document.getElementById(imgShow).src = Util.common.GetObjectURL(fileElement.files[0]);
                    Util.common.RevokeObjectURL(fileElement.files[0]);
                }
            }

            return file_size;
        }
    },
    file:{
        /**
         * 图片上传的公共弹出框
         * @author mahd
         * @param elem 单击事件对象
         * @param category 模块名称
         */
        UploadDialog:function UploadDialog(submitUrl, elem, category){
            var randomCode;
            if (category == null) {
                category = -1;
            }
            $.ajax({
                url: '/randomCode',
                data: {},
                type: 'post',
                dataType: 'text',
                success: function (randomCode) {
                    $("#randomCode").val(randomCode);
                    var arrStr="";
                    arrStr+="<iframe name='uploadPic' id='uploadPic' style='display: none' src=''></iframe>";
                    arrStr+="<form id='fileUploadForm' method='post' target='uploadPic' enctype='multipart/form-data' action='"+submitUrl+"'>";
                    arrStr+="<div id='J_tabs' class='dialog d-loadImg'>";
                    arrStr+="<div class='dialogBox'>";
                    arrStr+="<div class='bg-dialog'></div>";
                    arrStr+="<div class='d-RuleHead'>";
                    arrStr+="<ul>";
                    arrStr+="<li class='current'>本地上传</li>";
                    /*arrStr+="<li>浏览相册</li>";*/
                    arrStr+="</ul>";
                    arrStr+="<a href='javascript:void(0);' title='' onclick='Util.file.CloseWindow();' class='close'></a>";
                    arrStr+="</div>";
                    arrStr+="<div class='dialogCon'>";
                    //本地上传
                    arrStr+="<div class='d-loadImgCon current'>";
                    arrStr+="<div class='cf'>";
                    arrStr+="<div class='loadCon cf'>";
                    arrStr+="<input type='text' class='txt' id='filevalue'/>";
                    arrStr+="<input type='button' class='btn btn-table-01' id ='btn_upload' value='浏览'/>";
                    arrStr+="<input type='file' class='liul' name='uploadFile' id='uploadFile' onchange=\"document.getElementById('filevalue').value=this.value\"/>";
                    arrStr+="<a href='javascript:void(0);' style='height: 30px; margin-top: 20px; padding-top: 8px;' class='Flat_but' id='btnsub'>开始上传</a>";
                    arrStr+="<span id='errorMsg' style='float: left; font-size: 16px; margin-top: 20px;' class='red'></span></div>";
                    arrStr+="</div>";
                    //提示信息
                    arrStr+="</div>";
                    arrStr+="</div>";
                    //表单信息
                    //arrStr+="<input type='hidden' id='callBackUrl' name='callBackUrl' value='"+fileUploadBackUrl+"'/>";
                    arrStr+="<input type='hidden' id='category' name='category' value='"+category+"'/>";
                    arrStr+="<input type='hidden' id='randomCode' name='randomCode' value='"+randomCode+"'/>";
                    //arrStr+="<input type='submit' value='提交' style='display:none;' id='btn_sub'/>";
                    arrStr+="</div>";
                    arrStr+="</form>";
                    Util.file.MessageBox(submitUrl,elem,'选择图片',arrStr);
                },
                error: function (jqXHR) {
                    Util.window.Alert("服务出错，请联系客服人员处理。");
                }
            });
        },
        MessageBox:function MessageBox(submitUrl,elem,title,content){
            var objPos = Util.file.MousePosition(elem);
            messContent="<div style='padding:20px 0 20px 0;text-align:center'>"+content+"</div>";
            Util.file.ShowMessageBox(submitUrl,title,messContent,objPos,350);
        },
        //弹出方法
        ShowMessageBox:function ShowMessageBox(submitUrl,wTitle,content,pos,wWidth) {
            Util.file.CloseWindow();
            var bWidth=parseInt(document.documentElement.scrollWidth);
            var bHeight=parseInt(document.documentElement.scrollHeight);
            var styleStr="top:0px;left:0px;position:absolute;background:#ffff;width:"+bWidth+"px;height:"+bHeight+"px;z-index:0;";
            styleStr+=(isIe)?"filter:alpha(opacity=0);":"opacity:0;";
            var styleStrmesW="";
            styleStrmesW="z-index:1000;";
            styleStrmesW+="left:50%;top:70px;width:"+wWidth+"px;margin-left:-290px";
            if(isIe){
                Util.file.SetSelectState('hidden');
                var divstrback="";var divstrmesW="";
                divstrback+="<div id='back' ";
                divstrback+=" style='";
                divstrback+=styleStr;
                divstrback+="'></div>";
                $("body").prepend(divstrback);
                //showIeBackground('back',50);
                divstrmesW+="<div id='mesWindow' ";
                divstrmesW+=" style='";
                divstrmesW+=styleStrmesW;
                divstrmesW+="'>";
                divstrmesW+=content;
                divstrmesW+="</div>";
                $("body").prepend(divstrmesW);
                //document.createElement(divstrmesW);
            }else{
                var back=document.createElement("div");
                back.id="back";
                back.style.cssText=styleStr;
                document.body.appendChild(back);
                //showBackground(back,50);
                var mesW=document.createElement("div");
                mesW.id="mesWindow";
                mesW.style.cssText=styleStrmesW;
                mesW.innerHTML=content;
                document.body.appendChild(mesW);
            }
            //上传事件
            $("#btnsub").click(function(){
                var options = {
                    url: "/uac/uploadPortrait",
                    type:"POST",
                    dataType: "json",
                    beforeSubmit: function (){
                        if ($.trim($("#uploadFile").val()) == "") {
                            $("#errorMsg").html("请选择需要上传的图片。");
                            return false;
                        }
                        var pattern = /\.GIF$|\.JPEG$|\.JPG$|\.BMP$|\.PNG$/i;
                        if (!pattern.test($.trim($("#uploadFile").val()))) {
                            $("#errorMsg").html("图片格式必须为GIF、JPEG、JPG、BMP、PNG。");
                            return false;
                        }
                        return true;
                    },
                    success: function(data){
                        if (data.success) {
                            Util.window.Alert(data.message,"","", function(){
                                Util.file.CloseWindow();
                            });
                        } else {
                            if (data.message) {
                                $("#errorMsg").html(data.message,"","","");
                            } else {
                                $("#errorMsg").html("上传失败，请稍后重试或联系客服人员。");
                            }
                        }
                    },
                    error: function(XmlHttpRequest, textStatus, errorThrown){
                        $("#errorMsg").html("请求失败，请重试：有可能session失效,请重新登录。");
                    }
                };

                $("#fileUploadForm").ajaxSubmit(options);
            });
        },
        //关闭窗口
        CloseWindow:function CloseWindow() {
            if(document.getElementById('back')!=null){
                document.getElementById('back').parentNode.removeChild(document.getElementById('back'));
            }
            if(document.getElementById('mesWindow')!=null){
                document.getElementById('mesWindow').parentNode.removeChild(document.getElementById('mesWindow'));
            }
            if(isIe){
                Util.file.SetSelectState('');
            }
        },
        MousePosition:function MousePosition(ev){
            if(ev) {
                if(ev.pageX || ev.pageY) {
                    return {x:ev.pageX, y:ev.pageY};
                }
                return {
                    x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,y:ev.clientY + document.body.scrollTop - document.body.clientTop
                };
            }
            else {
                return {
                    //x:document.body.clientWidth / 2 + document.body.scrollLeft+150,y:document.body.clientHeight / 2 + document.body.scrollTop
                    x:document.documentElement.clientWidth / 2 + document.documentElement.scrollLeft+150,y:document.documentElement.clientHeight / 2 + document.documentElement.scrollTop
                };
            }
        },
        //设置select的可见状态
        SetSelectState:function setSelectState(state) {
            var objl=document.getElementsByTagName('select');
            for(var i=0;i<objl.length;i++){
                objl[i].style.visibility=state;
            }
        }
    },
    //弹出窗口处理
    window:{
        Show:function Show(message,title,btnName,callback,closeCallback){
            //网页可见区域宽度
            //var clientW=document.body.clientWidth;
            //var clientH=document.body.clientHeight;
            var htmlStr=new Array();
            htmlStr.push("<div class='dialog2' style='z-index:9999999' id='dia_div_'>");
            htmlStr.push("<div class='bg-dialog'></div>");
            htmlStr.push("<div class='dialogBox'>");
            htmlStr.push("<h2 style='font-size: 18px;  font-weight: bolder;'>"+((title==null||title=="")?tipArray[3]:title)+"<a href='#' class='close' name='di_close' title='关闭'>关闭</a></h2>");
            htmlStr.push("<div class='dialogCon'>");
            htmlStr.push("<div>");
            htmlStr.push("<p>"+message+"</p>");
            htmlStr.push("</div>");
            htmlStr.push("<div class='d-promptBtn'><a href='#' name='di_close' class='btn-red btn-save'>"+((btnName==null || btnName=="")?'确定':btnName)+"</a></div>");
            htmlStr.push("</div>");
            htmlStr.push("</div>");
            htmlStr.push("</div>");
            //隐藏层，用来遮罩BODY
            if($("#bgMask").length==0){
                $("body").prepend("<div id='bgMask' style='display:none;'><iframe></iframe></div>");
//	        		var height=$("html").height()+251;
//	        		var width=$("html").width();
                $("#dia_div_").css({"z-index":999999,"position":"absolute"});
            }
            $("body").prepend(htmlStr.join(""));
            $("#bgMask").show();
            //事件绑定
            $("a[name='di_close']").click(function(e){
                e.preventDefault();
                if(callback==null){
                    $("#bgMask").hide();
                    $("#dia_div_").remove();
                }else{
                    $("#bgMask").hide();
                    $("#dia_div_").remove();
                    if(closeCallback != undefined){
                        closeCallback(true);
                    }else if(callback != undefined){
                        callback(true);
                    }
                }
            });
        },
        //公共弹出框 标题默认为温馨提示 提示信息 确认按钮名称默认为确认 关闭回调（默认关闭弹出框）
        Alert:function Alert(message,title,btnName,callback,closeCallback){
            //网页可见区域宽度
            //var clientW=document.body.clientWidth;
            //var clientH=document.body.clientHeight;
            var htmlStr=new Array();
            htmlStr.push("<div class='dialog d-prompt' style='z-index:9999999' id='dia_div_'>");
            htmlStr.push("<div class='bg-dialog'></div>");
            htmlStr.push("<div class='dialogBox'>");
            htmlStr.push("<h2>"+((title==null||title=="")?tipArray[3]:title)+"<a href='#' class='close' name='di_close' title='关闭'>关闭</a></h2>");
            htmlStr.push("<div class='dialogCon'>");
            htmlStr.push("<div class='d-promptCon'>");
            htmlStr.push("<p>"+message+"</p>");
            htmlStr.push("</div>");
            htmlStr.push("<div class='d-promptBtn'><a href='#' name='di_close' class='btn-red btn-save'>"+((btnName==null || btnName=="")?'确定':btnName)+"</a></div>");
            htmlStr.push("</div>");
            htmlStr.push("</div>");
            htmlStr.push("</div>");
            //隐藏层，用来遮罩BODY
            if($("#bgMask").length==0){
                $("body").prepend("<div id='bgMask' style='display:none;'><iframe></iframe></div>");
//	        		var height=$("html").height()+251;
//	        		var width=$("html").width();
                $("#dia_div_").css({"z-index":999999,"position":"absolute"});
            }
            $("body").prepend(htmlStr.join(""));
            $("#bgMask").show();
            //事件绑定
            $("a[name='di_close']").click(function(e){
                e.preventDefault();
                if(callback==null){
                    $("#bgMask").hide();
                    $("#dia_div_").remove();
                }else{
                    $("#bgMask").hide();
                    $("#dia_div_").remove();
                    if(closeCallback != undefined){
                        closeCallback(true);
                    }else if(callback != undefined){
                        callback(true);
                    }
                }
            });
        },
        //确认框 参数1提示内容 参数2确认回调 参数3取消回调(默认关闭弹出框)  参数4标题 参数5确认按钮名称 参数6取消按钮名称
        Confirm:function Confirm(message,enCallBack,caCallBack,title,enBtnNme,caBtnName){
            if($("#confirm_div_").length>0){
                $("#confirm_div_").remove();
            }
            var idName="bgMask";
            if($.trim($("input[type='hidden'][name='pay']").val())=='1'){
                idName="bgMask-02";
            }
            enBtnNme = (enBtnNme==null||enBtnNme=='')?tipArray[0]:enBtnNme;
            caBtnName = (caBtnName==null||caBtnName=='')?tipArray[1]:caBtnName;
            var htmlStr=new Array();
            htmlStr.push("<div class='dialog d-risk' style='z-index:9999999;' id='confirm_div_'>");
            htmlStr.push("<div class='bg-dialog'></div>");
            htmlStr.push("<div class='dialogBox'>");
            htmlStr.push("<h2>"+title+"<a href='#' class='close' title='关闭' name='di_close'>关闭</a></h2>");
            htmlStr.push("<div class='dialogCon'>");
            htmlStr.push("<div class='d-riskInfo'>");
            htmlStr.push("<h3>"+message+"</h3>");
            htmlStr.push("</div>");
            htmlStr.push("<div class='d-riskBtn'>");
            htmlStr.push("<a href='#' id='di_en_btn' class='btn-red btn-save'>"+enBtnNme+"</a>");
            htmlStr.push("<a href='#' class='btn-normal btn-back' id='di_ca_btn'>"+caBtnName+"</a>");
            htmlStr.push("</div>");
            htmlStr.push("</div>");
            htmlStr.push("</div>");
            htmlStr.push("</div>");
            //隐藏层，用来遮罩BODY
            if($("#"+idName).length==0){
                $("body").prepend("<div id='"+idName+"' style='display:block;'><iframe></iframe></div>");
//        		var height=$("html").height()+251;
//        		var width=$("html").width();
                $("#confirm_div_").css({"z-index":999999,"position":"absolute"});
            }
            $("body").prepend(htmlStr.join(""));
            $("#"+idName).show();
            //事件绑定关闭事件
            $("a[name='di_close']").click(function(e){
                e.preventDefault();
                $("#"+idName).hide();
                $("#confirm_div_").remove();
                if(caCallBack!=null){
                    caCallBack();
                }
            });
            //确认按钮事件
            $("#di_en_btn").click(function(e){
                e.preventDefault();
                $("#"+idName).hide();
                $("#confirm_div_").remove();
                enCallBack();

            });
            //取消按钮事件
            $("#di_ca_btn").click(function(e){
                e.preventDefault();
                $("#"+idName).hide();
                $("#confirm_div_").remove();
                if(caCallBack!=null){
                    caCallBack();
                }
            });
        }
    },
    //分页处理
    pageTool:{
        /**
         * form表单用来给控件序列化参数，使用分页时请使用下列元素
         * <form name="pageForm" id="pageForm" method="post" action="<%=request.getContextPath()%>/demo/pageAjax">
         *     <input name="totalPage" id="totalPage" value="${result.page.totalPage}" type="hidden" />
         *     <input name="currentPage" id="currentPage" value="${result.page.currentPage}" type="hidden" />
         *     <input name="datasize" id="datasize" value="${fn:length(result.list)}" type="hidden"/>
         * </form>
         *  //模板生成页面存放位置
         *   <div id="pageResult" ></div>
         *   //分页工具栏
         *   <div id="pageNavTool"></div>
         *
         **/
        //初始化分页对象 支持刷新分页和ajax无刷新（回调自己处理响应结果，页码显示不需要考虑分页对象自动处理）
        //参数1(formId)  表单对象的ID 默认需要有如下数据和属性 action属性为业务请求地址 id为自定 调用init方法时需要传表单的id
        //参数2(pagediv)  显示分页工具条的DIV元素ID
        //参数3(callback)  AJAX回调
        //参数4(cache)  异步缓存分页
        //参数5(type)  提交方式
        //异步分页时callback需要传入回调方法
        //使用异步分页请求的结果处理可以在创建分页组件时指定
        //eg：
        // 1、异步分页(Jtemplate模板)方式:Util.pageTool.init("pageForm","pageNavTool",function(data){},null,"get");
        //    注：回调函数可不实现，但需加上，以此来判断是否做异步分页
        // 2、异步缓存分页（Jtemplate为模板,JPages做前端分页）:Util.pageTool.init("pageForm","pageNavTool",function(data),true,"get");
        // 3、表单提交时分页(无需模板):Util.pageTool.init("pageForm","pageNavTool",null,null,"get");
        init:function init(formId,pagediv,callback,cache,type){
            $("#" + pagediv).html("");
            $("#pageResult").html("<div class='loadPage'><p class='loadIoc'></p><p>数据正在加载中......</p></div>");
            //$("#"+pagediv).css({"padding-top":"20px","float":"right"});
            //$("#dataLoading").show();
            // 异步分页,需采用Jtemplate模板
            if (callback != null && cache == null) {
                $.ajax({
                    url: $("#" + formId).attr("action"),
                    data: $("#" + formId).serialize(),
                    type: type,
                    dataType:"json",
                    success: function (data) {
                        if (data != null) {
                            setTimeout(function(){
                                if (data.list == null || data.list.length == 0) {
                                    $("#pageResult").html("<div class='loadPage'><p class='no_data'></p></div>");
                                    callback(data);
                                } else {
                                    var dataList = data.list;
                                    $("#totalPage").val(parseInt(data['page']['totalPage']));
                                    $("#currentPage").val(parseInt(data['page']['currentPage']));
                                    var formdata = Util.pageTool.formParamsInit(formId);
                                    $("#" + pagediv).html(Util.pageTool.createNavTool(formdata, dataList.length));
                                    // 附上模板
                                    $("#pageResult").setTemplateElement("template");
                                    // 给模板加载数据
                                    $("#pageResult").processTemplate(dataList);
                                    callback(data);
                                    $("span[class='pagetool_pageButton']").click(function (e) {
                                        e.preventDefault();
                                        $("#currentPage").val(parseInt($(this).attr("value")));
                                        Util.pageTool.init(formId, pagediv, callback, cache,type);
                                    });
                                }
                            }, 350);
                        }
                    }
                });
            }
            //支持异步缓存分页,减少与服务器通讯，需采用Jtemplate模板
            else if(callback==null&&cache==true){
                $.ajax({
                    url: $("#"+formId).attr("action"),
                    async:false,
                    data:$("#"+formId).serialize(),
                    type:type,
                    success:function(data){
                        setTimeout(function(){
                            if (data.list == null || data.list.length == 0) {
                                $("#pageResult").html("<div class='loadPage'><p class='no_data'></p></div>");
                            } else {
                                if (data != null) {
                                    // 附上模板
                                    $("#pageResult").setTemplateElement("template");
                                    // 给模板加载数据
                                    var temp = $("#pageResult").processTemplate(data.list);
                                    //对模板数据进行分页
                                    $(function () {
                                        $("#pageNavTool").jPages({
                                            containerID: "tbody",
                                            previous: "←",
                                            startPage: data['page'].currentPage + 5,
                                            perPage: 1,
                                            delay: 20,
                                            callback: function (pages, items) {
                                                /*                                        console.info('当前页面:',pages.current);
                                                 console.info('页面总数:',pages.count);
                                                 console.info('总数量:',items.count);
                                                 console.info('每页数量:',items.count/pages.count);*/
                                                //如果总页数大于当前缓存分页大小，显示下10页按钮
                                                if (data['page'
                                                        ].totalRecord > items.count) {
                                                    $("#pageSize").val((data['page'].totalRecord / items.count + 1) * data['page'].pageSize);
                                                    if ($("a[ lang='f']")[0] == undefined) {
                                                        $("#pageNavTool").append("<a lang='f' href='javascript:void(0)' onclick=" + 'javascript:Util.pageTool.init("pageForm","pageNavTool","qqq",null);' + ">下10页</a>");
                                                    }
                                                }
                                            }
                                        });
                                    });
                                }
                            }
                        }, 350);
                    }
                });
                $("span[class='pagetool_pageButton']").click(function(e){
                    e.preventDefault();
                    $("#currentPage").val(parseInt($(this).attr("value")));
                    Util.pageTool.init(formId,pagediv,callback,autoload);
                });
            }
            //同步方式分页
            else if(cache==null && callback==null){
                $("#pageResult").html("");
                var formdata=Util.pageTool.formParamsInit(formId);
                $("#"+pagediv).html(Util.pageTool.createNavTool(formdata,parseInt($("#datasize").val())));
                $("span[class='pagetool_pageButton']").click(function(e){
                    e.preventDefault();
                    $("#currentPage").val(parseInt($(this).attr("value")));
                    $("#"+formId).submit();
                });
            }
        },

        //根据总信息数创建页码
        createNavTool:function createNavTool(data,dataLength){
            var re="";
            if(dataLength>0){
                var totalPage=parseInt(data.totalPage);
                var currentPage=parseInt(data.currentPage);
                if (totalPage <currentPage) {
                    currentPage =totalPage;
                }
                if(totalPage<=1){
                    return "";
                }
                //第一页
                if (currentPage <= 1) {
                    currentPage = 1;
                } else {
                    //非第一页
                    re += Util.pageTool.printHtml(currentPage - 1, totalPage, "上一页");
                    //总是显示第一页页码
                    re += Util.pageTool.printHtml(1, totalPage, "1");
                }
                //开始页码
                var start = 2;
                var end = (totalPage < 5) ? totalPage: 5;
                //是否显示前置省略号,即大于10的开始页码
                if (currentPage >= 5) {
                    re += page_span_more;
                    start = currentPage - 2;
                    var e = currentPage + 2;
                    end = (totalPage < e) ? totalPage: e;
                }
                for (var i = start; i <currentPage; i++) {
                    re += Util.pageTool.printHtml(i, totalPage);
                };
//				    if(dataLength>1){
                re += Util.pageTool.printHtml2(currentPage);
//				    }
                for (var i = currentPage + 1; i <= end; i++) {
                    re += Util.pageTool.printHtml(i, totalPage);
                };
                if (end < totalPage) {
                    re +=page_span_more;
                    //显示最后一页页码,如不需要则去掉下面这一句
                    re += Util.pageTool.printHtml(totalPage, totalPage);
                };
                if (currentPage < totalPage) {
                    re += Util.pageTool.printHtml(currentPage + 1, totalPage, "下一页");
                };
//				    if(!dataLength>1){
//				    	if(currentPage==totalPage){
//					    	re += PageTool.printHtml2(currentPage);
//					    }
//				    }

            }
            return re;
        },
        //将表单的值格式为可直接访问的JSON对象
        formParamsInit:function formParamsInit(formId){
            var obj=$("#"+formId).serializeArray();
            var data={};
            $.each(obj,function(){
                if(data[this.name]){
                    if(data[this.name].push){
                        data[this.name]=[data[this.name]];
                    }
                    data[this.name].push(this.value || '');
                }else{
                    data[this.name]=this.value || '';
                }
            });
            return data;
        },
        //选中时的页码样式
        printHtml2:function printHtml2(pageNo) {
            var H="<span class='pagetool_pageButton pagetool_pageButton_current' classname='pagetool_pageButton pagetool_pageButton_current' innerhtml='"+pageNo+"' textcontent='"+pageNo+"' value='"+pageNo+"'>"+pageNo+"</span>";
            //var H = " <span class='cPageNum' lang='"+pageNo+"'>" + pageNo + "</span> ";
            return H;
        },
        //没有选中时的页码样式
        printHtml:function printHtml(pageNo, pn, showPageNo,callback) {
            showPageNo = showPageNo || pageNo;
            //var H = " <a href='#' class='pageNum' lang='"+pageNo+"'>" + showPageNo + "</a> ";
            var H="";
            if($.trim(showPageNo)=='上一页' || $.trim(showPageNo)=='下一页'){
                H="<span class='pagetool_pageButton' classname='pagetool_pageButton' innerhtml='"+pageNo+"' textcontent='1' value='"+pageNo+"'>"+showPageNo+"</span>";
            }else{
                H="<span class='pagetool_pageButton' classname='pagetool_pageButton' innerhtml='"+pageNo+"' textcontent='1' value='"+pageNo+"'>"+showPageNo+"</span>";
            }
            return H;
        }
    }
};

//收起所有选项卡
function packUpAllMenu(){
    $("#vt_loan_p").css("display","none");
    $("#vt_borrow_p").css("display","none");
    $("#vt_fund_p").css("display","none");
    $("#vt_bonus_p").css("display","none");
    $("#vt_friend_p").css("display","none");
    $("#vt_info_p").css("display","none");
}

/**
 * 打开一级菜单，高亮显示二级菜单
 * @param id 当前id
 */
function openSecondMenu(first_id,second_id){
    var currentClass="#1f96d4 none repeat scroll 0 0";
    $("#"+first_id+"_p").css("display","block");
    $("#"+second_id).css("background",currentClass);
}

//通过回调来设置向用户显示的图片
function setInfoPicUrl(picurl,code,type){
    if(code == '1' ){
        $("#imgPlace").attr("src",picurl);
        $("#pic_url").val(picurl);
        Util.file.CloseWindow();
    }else{
        Util.window.Alert("图片上传失败","确定");
        //alert('图片上传失败');
    }
}
var page_span_more="<span style='float:left;'>.....</span>";

function StringBuffer() {
    this.__strings__ = new Array;
}

StringBuffer.prototype.append = function (str) {
    this.__strings__.push(str);
};

StringBuffer.prototype.toString = function () {
    return this.__strings__.join("");
};

var uploadPreview = function(setting) {
    /*
     *this(当前对象)
     */
    var _self = this;
    /*
     *判断为null或者空值
     */
    _self.IsNull = function(value) {
        if (typeof (value) == "function") { return false; }
        if (value == undefined || value == null || value == "" || value.length == 0) {
            return true;
        }
        return false;
    }
    /*
     *默认配置
     */
    _self.DefautlSetting = {
        UpBtn: "UpBtn",
        DivShow: "DivShow",
        ImgShow: "ImgShow",
        MsgShow: "MsgShow",
        MaxSize: 2048,//KB
        Width: 200,
        Height: 200,
        ImgType: ["gif", "jpeg", "jpg", "bmp", "png"],
        ErrMsg: "选择文件错误,图片类型必须是(gif,jpeg,jpg,bmp,png)中的一种",
        callback: function(file) {_self.revokeObjectURL(file);}
    };
    /*
     *读取配置
     */
    _self.Setting = {
        UpBtn: _self.IsNull(setting.UpBtn) ? _self.DefautlSetting.UpBtn : setting.UpBtn,
        DivShow: _self.IsNull(setting.DivShow) ? _self.DefautlSetting.DivShow : setting.DivShow,
        ImgShow: _self.IsNull(setting.ImgShow) ? _self.DefautlSetting.ImgShow : setting.ImgShow,
        MsgShow: _self.IsNull(setting.MsgShow) ? _self.DefautlSetting.MsgShow : setting.MsgShow,
        MaxSize: _self.IsNull(setting.MaxSize) ? _self.DefautlSetting.MaxSize : setting.MaxSize,
        Width: _self.IsNull(setting.Width) ? _self.DefautlSetting.Width : setting.Width,
        Height: _self.IsNull(setting.Height) ? _self.DefautlSetting.Height : setting.Height,
        ImgType: _self.IsNull(setting.ImgType) ? _self.DefautlSetting.ImgType : setting.ImgType,
        ErrMsg: _self.IsNull(setting.ErrMsg) ? _self.DefautlSetting.ErrMsg : setting.ErrMsg,
        callback: _self.IsNull(setting.callback) ? _self.DefautlSetting.callback : setting.callback
    };
    /*
     *获取文本控件URL
     */
    _self.getObjectURL = function(file) {
        var url = null;
        if (window.createObjectURL != undefined) {
            url = window.createObjectURL(file);
        } else if (window.URL != undefined) {
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) {
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }
    /*
     *释放图片内存
     */
    _self.revokeObjectURL = function(file) {
        if (window.createObjectURL != undefined) {
            window.revokeObjectURL(file);
        } else if (window.URL != undefined) {
            window.URL.revokeObjectURL(file);
        } else if (window.webkitURL != undefined) {
            window.webkitURL.revokeObjectURL(file);
        }
    }
    /*
     *绑定事件
     */
    _self.Bind = function() {
        document.getElementById(_self.Setting.UpBtn).onchange = function() {
            if (this.value) {
                if (!RegExp("\.(" + _self.Setting.ImgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
                    document.getElementById(_self.Setting.MsgShow).innerHTML = "图片格式必须为"+_self.Setting.ImgType.join("，")+"。";
                    return false;
                }

                if (_self._IE()) {
                    try {
                        if(_self._size(this.files[0])){
                            return false;
                        }
                        document.getElementById(_self.Setting.ImgShow).src = _self.getObjectURL(this.files[0]);
                        _self.Setting.callback(this.files[0]);
                    } catch (e) {
                        var div = document.getElementById(_self.Setting.DivShow);
                        this.select();
                        top.parent.document.body.focus();
                        var src = document.selection.createRange().text;
                        var isBigger = false;
                        var file_size = -99;
                        var sh = setInterval(
                            function(){
                                var img = document.createElement("img");
                                img.src = src;
                                file_size = img.fileSize;

                                if (file_size > 0) {
                                    // 转化为kb和MB格式。文件的名字、大小、类型都是可以现实出来。
                                    var sizeShow;
                                    if (file_size > 1024 * 1024) {
                                        sizeShow = (Math.round(file_size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
                                    } else {
                                        sizeShow = (Math.round(file_size * 100 / 1024) / 100).toString() + 'KB';
                                    }
                                    if (file_size > 1024 * _self.Setting.MaxSize) {
                                        document.getElementById(_self.Setting.MsgShow).innerHTML = "上传的文件[" + sizeShow + "]大于" + _self.Setting.MaxSize + "KB，请重新选择。";
                                        document.getElementById(_self.Setting.MsgShow).style.color="red";
                                        isBigger = true;
                                    } else {
                                        document.getElementById(_self.Setting.MsgShow).innerHTML = "图片大小："+file_size+"。";
                                        document.getElementById(_self.Setting.MsgShow).style.color="#555";
                                    }
                                }
                                img = null;
                            }
                            ,100
                        );
                        if(isBigger){
                            return false;
                        }

                        document.selection.empty();
                        document.getElementById(_self.Setting.ImgShow).style.display = "none";
                        div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                        div.style.width = _self.Setting.Width + "px";
                        div.style.height = _self.Setting.Height + "px";
                        div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src;
                    }
                } else {
                    if(_self._size(this.files[0])){
                        return false;
                    }
                    document.getElementById(_self.Setting.ImgShow).src = _self.getObjectURL(this.files[0]);
                    _self.Setting.callback(this.files[0]);
                }
            }
        }
    }

    _self._IE = function(){
        var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
        while (
            div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
                all[0]
            );
        return v > 4 ? v : ("ActiveXObject" in window);
    }

    _self._size = function(file){//返回是否超过限制。
        var file_size = file.size;

        if (file_size > 0) {

            // 转化为kb和MB格式。文件的名字、大小、类型都是可以现实出来。
            var sizeShow;
            if (file_size > 1024 * 1024) {
                sizeShow = (Math.round(file_size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
            } else {
                sizeShow = (Math.round(file_size * 100 / 1024) / 100).toString() + 'KB';
            }

            if (file_size > 1024 * _self.Setting.MaxSize) {
                document.getElementById(_self.Setting.MsgShow).innerHTML = "上传的文件[" + sizeShow + "]大于" + _self.Setting.MaxSize + "KB，请重新选择。";
                document.getElementById(_self.Setting.MsgShow).style.color="red";
                return true;
            }

            document.getElementById(_self.Setting.MsgShow).innerHTML = "图片大小："+sizeShow+"。";
            document.getElementById(_self.Setting.MsgShow).style.color="#555";
        }

        return false;
    }
    /*
     *执行绑定事件
     */
    _self.Bind();
}